<template>
  <div class="app">
<!--    <h1>Next player: {{ currentPlayer }}</h1>-->
    <h1>{{ heading }}</h1>
    <BoardComponent
      @click-square="handleClick"
      :results="results"
      :winner-line="winnerArr"
    />
  </div>
</template>

<script>
import BoardComponent from "@/components/BoardComponent";

const lines = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6],
]

export default {
  name: 'App',
  data() {
    return {
      heading: "Next player: x",
      results: new Array(9).fill(null),
      nextPlayIsX: true,
      winnerArr: []
    }
  },
  computed: {
    currentPlayer() {
      return this.nextPlayIsX ? "x" : "o"
    }
  },
  components: {
    BoardComponent,
  },
  methods: {
    handleClick(index) {
      if (this.results[index]) {
        return
      }
      // console.log("被点击了", index)
      // console.log(this.results)
      // this.results[index] = "x"
      const res = this.results.slice()
      // res[index] = "x"
      res[index] = this.nextPlayIsX ? "x" : "o"
      // 返回一个新的值
      this.results = res
      // 切换选手
      this.nextPlayIsX = !this.nextPlayIsX
      this.heading = this.nextPlayIsX ? "Next player: x" : "Next player: o"
      // check winner
      console.log(this.results)

      for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i]
        if (this.results[c]) { // 排除 null
          // a === b === c
          if (this.results[c] === this.results[b] && this.results[c] === this.results[a]) {
            console.log("winner is ", this.results[c])
            console.log(lines[i])
            this.winnerArr = lines[i]
            this.heading = "winner is: "+ this.results[c]
            return;
          }
        }
      }
    }
  }
}
</script>

<style>
/*@import "~normalize.css";*/
.app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}
</style>
